import { Module } from '@nestjs/common'
import { TypeOrmModule } from "@nestjs/typeorm";
import * as path from "path";
import * as dayjs from 'dayjs';
import { FileService } from './file.service'
import { FileController } from './file.controller'
import { MulterModule } from "@nestjs/platform-express"
import { SnowflakeId } from "@libs/snowflake.id"
import { diskStorage } from "multer"
import { Request } from 'express'
import { Express } from "express"
import { checkDirAndCreate, getExtName } from "@utils/file";
import { FileEntity, FileBusinessEntity } from "@entities/file.entity";
import { isImage } from "@utils/file";
import { ConfigService } from "@config/config.service";
import { ServerException } from "@exceptions";

/**
 * 文件上传注册
 * @constructor
 */
const MulterModuleRegister = () => {
    const config = new ConfigService(process.env.NODE_ENV)
    return MulterModule.register({
        // 配置文件上传后的文件夹路径
        storage: diskStorage({
            destination: (req: Request, file: Express.Multer.File, callback: (error: (Error | null), filename: string) => void) => {
                try {
                    const extName = getExtName(file.originalname).toLowerCase(); //获取文件后缀名
                    const source = req.headers['source']; //附件来源
                    const category = isImage(extName) ? 'images' : extName // 文件分类
                    const filePath = `${config['UPLOAD_DIR']}${category}/${dayjs().format('YYYY-MM-DD')}`;
                    file['source'] = source;
                    file['filePath'] = filePath
                    checkDirAndCreate(filePath); // 判断文件夹是否存在，不存在则自动生成
                    return callback(null, `./${filePath}`);
                } catch (e) {
                    throw new ServerException(e)
                }
            },

            // 在此处自定义保存后的文件名称
            filename(req: Request, file: Express.Multer.File, callback: (error: (Error | null), filename: string) => void) {
                try {
                    const fileId = SnowflakeId.generate(); //获取文件后缀名
                    const extName = getExtName(file.originalname); //生成文件名
                    const filename = `${fileId}.${extName}`; //生成文件id
                    file['fileId'] = fileId;
                    file['savePath'] = path.join(file['filePath'], filename);
                    file['suffix'] = getExtName(filename);
                    return callback(null, filename);
                } catch (e) {
                    throw new ServerException(e)
                }
            }
        })
    })
}

@Module({
    imports: [
        TypeOrmModule.forFeature([FileEntity, FileBusinessEntity]),
        MulterModuleRegister()
    ],
	controllers: [FileController],
	providers: [FileService]
})
export class FileModule {}
